package com.common.exception;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerExceptionResolverComposite;

import com.common.util.StringUtil;

public class CommonException extends HandlerExceptionResolverComposite {

	
	 
	 public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		    response.setCharacterEncoding(ExceptionConstant.ENCODE_UTF_8);
            response.setContentType("text/plain");
			try {
			    PrintWriter writer = response.getWriter();
			    response.setStatus(500);
			     //人为异常处理
			     if(ex instanceof BusinessException &&!StringUtil.isEmpty(((BusinessException) ex).getErrorCode())){
			    	 //依据异常代码
			    	 writer.write("错误代码:"+((BusinessException) ex).getErrorCode()+","+ex.getMessage());
			    	 System.out.println("错误代码:"+((BusinessException) ex).getErrorCode()+"::"+ex.getMessage());
			     }else if(ex instanceof BusinessException) {
			    	 //默认逻辑校验
			    	 writer.write("错误代码:"+ExceptionConstant.ERROR_CODE_0003+","+ex.getMessage());
			    	 System.out.println("错误代码:"+ExceptionConstant.ERROR_CODE_0003+"::"+ex.getMessage());
			     }else{
			    	 //虚拟机异常
			    	 writer.write("错误代码:"+ExceptionConstant.ERROR_CODE_9999);
			    	 System.out.println("错误代码:"+ExceptionConstant.ERROR_CODE_9999+"::"+ex.getMessage());
			     }
				 writer.flush();
				 writer.close();
		} catch (IOException e) {

		}
		return null;
	}  

}
